package com.iplant.mes.controller.sfc;

import com.iplant.ams.service.po.dms.scada.conf.DMSDeviceParameter;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.mes.service.SFCFrockBindService;
import com.iplant.mes.service.SFCService;
import com.iplant.mes.service.mesenum.sfc.SFCTaskStatus;
import com.iplant.mes.service.po.sfc.SFCTaskReport;
import com.iplant.mes.service.po.sfc.SFCTaskStartCheck;
import com.iplant.mes.service.po.sfc.SFCWorkpieceRecord;
import com.iplant.mes.service.po.sfc.workpieceRecord.SFCExportHead;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/SFCWorkpieceRecord")
public class SFCWorkpieceRecordController extends BasicController<SFCWorkpieceRecord> {
    private static final Logger logger = LoggerFactory.getLogger(SFCWorkpieceRecordController.class);

    public SFCWorkpieceRecordController() {
        super(SFCWorkpieceRecord.class);
    }

    @Autowired
    SFCService mSFCService;

    @Autowired
    SFCFrockBindService mSFCFrockBindService;

    /**
     * 条件查询
     */
    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wMaterialBarcode = StringUtils.parseString(request.getParameter("MaterialBarcode"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("CStartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("CEndTime"));
            int wDeviceID = StringUtils.parseInt(request.getParameter("DeviceID"));
            int wStationID = StringUtils.parseInt(request.getParameter("StationID"));
            Pagination wPagination = GetPagination(request, mClazz);
            Map<String, Object> wParams = GetParamsMap(request);

            ServiceResult<List<SFCWorkpieceRecord>> wServiceResult = mSFCService.SFC_WorkpieceRecordAll(wLoginUser,
                    wMaterialBarcode, wStartTime, wEndTime, wParams, wDeviceID, wStationID, wPagination);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 查询工件流转详情
     */
    @GetMapping("/QueryWorkpieceCirculateDetails")
    public Object QueryWorkpieceCirculateDetails(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wWorkpieceResumeID = StringUtils.parseInt(request.getParameter("WorkpieceResumeID"));

            if (wWorkpieceResumeID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_QueryWorkpieceCirculateDetails(wLoginUser,
                    wWorkpieceResumeID);
            if (!wServiceResult.CustomResult.containsKey("FistCheckItems")) {
                wServiceResult.CustomResult.put("FistCheckItems", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("FistCheckValues")) {
                wServiceResult.CustomResult.put("FistCheckValues", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("SelfCheckItems")) {
                wServiceResult.CustomResult.put("SelfCheckItems", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("SelfCheckValues")) {
                wServiceResult.CustomResult.put("SelfCheckValues", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("MaterialDatas")) {
                wServiceResult.CustomResult.put("MaterialDatas", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("StartCheckData")) {
                wServiceResult.CustomResult.put("StartCheckData", new SFCTaskStartCheck());
            }
            if (!wServiceResult.CustomResult.containsKey("MutualCheckItems")) {
                wServiceResult.CustomResult.put("MutualCheckItems", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("MutualCheckValues")) {
                wServiceResult.CustomResult.put("MutualCheckValues", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("SpecialCheckItems")) {
                wServiceResult.CustomResult.put("SpecialCheckItems", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("SpecialCheckValues")) {
                wServiceResult.CustomResult.put("SpecialCheckValues", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("TaskReport")) {
                wServiceResult.CustomResult.put("TaskReport", new SFCTaskReport());
            }
            if (!wServiceResult.CustomResult.containsKey("TaskReportItems")) {
                wServiceResult.CustomResult.put("TaskReportItems", new ArrayList<>());
            }
            if (!wServiceResult.CustomResult.containsKey("WriteParamItems")) {
                wServiceResult.CustomResult.put("WriteParamItems", new ArrayList<>());
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 工件报废
     */
    @PostMapping("/Scrap")
    public Object Scrap(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            SFCWorkpieceRecord wSFCWorkpieceRecord = CloneTool.Clone(wParam.get("data"), SFCWorkpieceRecord.class);
            if (wSFCWorkpieceRecord == null || wSFCWorkpieceRecord.ID <= 0 || wSFCWorkpieceRecord.Status == SFCTaskStatus.Scarp.getValue()) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_WorkpieceRecordScrap(wLoginUser,
                    wSFCWorkpieceRecord);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 查询工件作业详情
     */
    @GetMapping("/QueryWorkpiecesJobDetails")
    public Object QueryWorkpiecesJobDetails(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wWorkpieceRecordID = StringUtils.parseInt(request.getParameter("WorkpieceRecordID"));
            if (wWorkpieceRecordID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<SFCWorkpieceRecord> wServiceResult = mSFCService.SFC_QueryWorkpiecesJobDetails(wLoginUser,
                    wWorkpieceRecordID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询工件在设备下的参数
     */
    @GetMapping("/QueryParams")
    public Object QueryParams(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wWorkpieceNo = StringUtils.parseString(request.getParameter("WorkpieceNo"));
            int wRoutePartID = StringUtils.parseInt(request.getParameter("RoutePartID"));
            int wRoutePartPointID = StringUtils.parseInt(request.getParameter("RoutePartPointID"));
            int wStationID = StringUtils.parseInt(request.getParameter("StationID"));

            ServiceResult<List<DMSDeviceParameter>> wServiceResult = mSFCService.SFC_QueryParams(wLoginUser,
                    wWorkpieceNo,
                    wRoutePartID, wRoutePartPointID, wStationID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询工件在设备下的参数
     */
    @GetMapping("/QueryParamsByStationIDs")
    public Object QueryParamsByStationIDs(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            List<Integer> wStationIDs = StringUtils.parseIntList(request.getParameter("StationIDs"), ",");
            List<Integer> wDataClassList = StringUtils.parseIntList(request.getParameter("DataClass"), ",");

            if (wStationIDs == null || wStationIDs.size() <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<List<DMSDeviceParameter>> wServiceResult = mSFCService.QueryParamsByStationIDs(wLoginUser,
                    wStationIDs, wDataClassList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询工件在设备下的参数曲线记录
     */
    @GetMapping("/QueryDeviceRecord")
    public Object QueryDeviceRecord(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wWorkpieceNo = StringUtils.parseString(request.getParameter("WorkpieceNo"));
            int wRoutePartID = StringUtils.parseInt(request.getParameter("RoutePartID"));
            int wRoutePartPointID = StringUtils.parseInt(request.getParameter("RoutePartPointID"));
            int wStationID = StringUtils.parseInt(request.getParameter("StationID"));
            int wDeviceID = StringUtils.parseInt(request.getParameter("DeviceID"));

            ServiceResult<List<Map<String, Object>>> wServiceResult = mSFCService.QueryDeviceRecord(wLoginUser,
                    wWorkpieceNo,
                    wRoutePartID, wRoutePartPointID, wStationID, wDeviceID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 导出曲线记录
     */
    @PostMapping("/Export")
    public Object Export(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wWorkpieceNo = StringUtils.parseString(wParam.get("WorkpieceNo"));
            int wRoutePartID = StringUtils.parseInt(wParam.get("RoutePartID"));
            int wRoutePartPointID = StringUtils.parseInt(wParam.get("RoutePartPointID"));
            int wDeviceID = StringUtils.parseInt(wParam.get("DeviceID"));
            String wDeviceName = StringUtils.parseString(wParam.get("DeviceName"));
            List<SFCExportHead> wHeadList = CloneTool.CloneArray(wParam.get("HeadList"), SFCExportHead.class);

            ServiceResult<String> wServiceResult = mSFCFrockBindService.SFC_ExportDeviceRecord(wLoginUser, wWorkpieceNo,
                    wRoutePartID, wRoutePartPointID, wDeviceID, wHeadList, wDeviceName);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
